from typing import Dict, Callable, Type
from src.events import Event
from src.event_bus import EventBus
from PySide6.QtCore import QModelIndex

# 导入事件类型
from src.events import (
    CellEditedEvent, RowAddedEvent, RowInsertedEvent, RowDeletedEvent,
    ColumnAddedEvent, ColumnInsertedEvent, ColumnRemovedEvent,
    ColumnReorderedEvent, ColumnMarkedEvent, RowStatusChangedEvent,
    DataLoadedEvent, DataSavedEvent
)

# 导入操作类型
from src.backend.undo_manager import OperationType


class EventHandler:
    """事件处理器基类"""
    pass


class FrontendEventHandler(EventHandler):
    """前端事件处理器"""
    
    def __init__(self, main_window):
        self.main_window = main_window
        
    def handle_cell_edited(self, event: 'CellEditedEvent'):
        """处理单元格编辑事件"""
        # 记录撤销操作
        self.main_window._undo_manager.add_operation(
            OperationType.UPDATE_CELL,
            {
                'row': event.row,
                'col': event.col,
                'old_value': event.old_value,
                'new_value': event.new_value
            },
            f"更新单元格 [{event.row}, {event.col}]: '{event.old_value}' -> '{event.new_value}'"
        )
        
        # 更新UI状态
        self.main_window._update_status()
        
    def handle_row_added(self, event: 'RowAddedEvent'):
        """处理行添加事件"""
        # 记录撤销操作
        self.main_window._undo_manager.add_operation(
            OperationType.INSERT_ROW,
            {
                'row_index': event.row_index,
                'row_data': event.row_data.copy()
            },
            f"添加新行 {event.row_index}"
        )
        
        # 更新表格视图
        if self.main_window._fixed_model and self.main_window._scroll_model:
            # 使用正确的行插入通知
            new_row = event.row_index
            self.main_window._fixed_model.beginInsertRows(QModelIndex(), new_row, new_row)
            self.main_window._fixed_model.endInsertRows()
            self.main_window._scroll_model.beginInsertRows(QModelIndex(), new_row, new_row)
            self.main_window._scroll_model.endInsertRows()
            
        self.main_window._update_status()
        
    def handle_row_inserted(self, event: 'RowInsertedEvent'):
        """处理行插入事件"""
        # 记录撤销操作
        self.main_window._undo_manager.add_operation(
            OperationType.INSERT_ROW,
            {
                'row_index': event.row_index,
                'row_data': event.row_data.copy()
            },
            f"在位置 {event.row_index} 插入行"
        )
        
        # 更新表格视图
        if self.main_window._fixed_model and self.main_window._scroll_model:
            # 使用正确的行插入通知
            position = event.row_index
            self.main_window._fixed_model.beginInsertRows(QModelIndex(), position, position)
            self.main_window._fixed_model.endInsertRows()
            self.main_window._scroll_model.beginInsertRows(QModelIndex(), position, position)
            self.main_window._scroll_model.endInsertRows()
            
        self.main_window._update_status()
        
    def handle_row_deleted(self, event: 'RowDeletedEvent'):
        """处理行删除事件"""
        # 记录撤销操作
        self.main_window._undo_manager.add_operation(
            OperationType.DELETE_ROW,
            {
                'row_index': event.row_index,
                'row_data': event.row_data.copy()
            },
            f"删除行 {event.row_index}"
        )
        
        # 更新表格视图
        if self.main_window._fixed_model and self.main_window._scroll_model:
            # 通知模型数据已更改，而不是删除行（因为DataManager已经处理了删除）
            self.main_window._fixed_model.refresh_data()
            self.main_window._scroll_model.refresh_data()
            
        self.main_window._update_status()
        
    def handle_column_reordered(self, event: 'ColumnReorderedEvent'):
        """处理列重排序事件"""
        # 记录撤销操作
        self.main_window._undo_manager.add_operation(
            OperationType.REORDER_COLUMNS,
            {
                'old_order': event.old_order.copy(),
                'new_order': event.new_order.copy()
            },
            "重新排序列"
        )
        
        # 更新表格视图 - 使用静默模式避免递归
        if self.main_window._fixed_model and self.main_window._scroll_model:
            # 检查当前顺序是否与事件中的新顺序一致
            current_fixed_order = self.main_window._fixed_model.get_column_order()
            current_scroll_order = self.main_window._scroll_model.get_column_order()
            
            # 只有当顺序确实发生变化时才更新，避免递归
            if current_fixed_order != event.new_order:
                self.main_window._fixed_model.set_column_order(event.new_order, silent=True)
            if current_scroll_order != event.new_order:
                self.main_window._scroll_model.set_column_order(event.new_order, silent=True)
                
            self.main_window._update_frozen_columns()
            
        self.main_window._update_status()
        
    def handle_column_marked(self, event: 'ColumnMarkedEvent'):
        """处理列标记事件"""
        # 记录撤销操作
        self.main_window._undo_manager.add_operation(
            OperationType.MARK_COLUMNS,
            {
                'old_marked': event.old_marked.copy(),
                'new_marked': event.new_marked.copy()
            },
            "设置列标识"
        )
        
        # 更新表格视图
        if self.main_window._fixed_model and self.main_window._scroll_model:
            # 检查新旧标记是否相同，避免递归
            fixed_marked = self.main_window._fixed_model.get_marked_columns()
            scroll_marked = self.main_window._scroll_model.get_marked_columns()
            
            # 只有当标记发生变化时才更新
            if fixed_marked != event.new_marked or scroll_marked != event.new_marked:
                self.main_window._fixed_model.set_marked_columns(event.new_marked)
                self.main_window._scroll_model.set_marked_columns(event.new_marked)
                
            # 始终更新视图范围和冻结列设置，确保UI同步
            self.main_window._update_frozen_columns()
            self.main_window._update_view_ranges()
            
        self.main_window._update_status()
        
    def handle_column_inserted(self, event: 'ColumnInsertedEvent'):
        """处理列插入事件"""
        # 记录撤销操作
        self.main_window._undo_manager.add_operation(
            OperationType.INSERT_COLUMN,
            {
                'position': event.col_index,
                'header': event.header,
                'default_value': event.default_value,
                'col_index': event.col_index
            },
            f"插入列 {event.header} 于位置 {event.col_index}"
        )
        
        # 更新表格视图
        if self.main_window._fixed_model and self.main_window._scroll_model:
            # 刷新两个模型的数据
            self.main_window._fixed_model.refresh_data()
            self.main_window._scroll_model.refresh_data()
            
            # 更新视图范围和冻结列设置，确保UI同步
            self.main_window._update_frozen_columns()
            self.main_window._update_view_ranges()
            
        self.main_window._update_status()


class BackendEventHandler(EventHandler):
    """后端事件处理器"""
    
    def __init__(self, data_manager):
        self.data_manager = data_manager
        
    def handle_data_loaded(self, event: 'DataLoadedEvent'):
        """处理数据加载事件"""
        # 执行数据加载后的操作
        pass
        
    def handle_data_saved(self, event: 'DataSavedEvent'):
        """处理数据保存事件"""
        # 执行数据保存后的操作
        pass
